package com.kechelle.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
public class JDBCController {

    @Autowired
    JdbcTemplate jdbcTemplate;

    //查询数据库的所有信息
    @GetMapping("/userList")
    public List<Map<String,Object>> userList(){
        String sql = "select * from user";
        List<Map<String,Object>> mapList = jdbcTemplate.queryForList(sql);
        return mapList;
    }

    //增加用户
    @GetMapping("/addUser")
    public String addUser(){
        String sql = "insert into mydb.user(id,name,pwd) values (6,'小明','123456')";
        jdbcTemplate.update(sql);
        return "add~ok";
    }

    //修改用户
    @GetMapping("/updateUser/{id}")
    public String updateUser(@PathVariable("id") int id){
        String sql = "update mydb.user set name=?,pwd=? where id=" + id;
        //封装参数
        Object[] objects = new Object[2];
        objects[0] = "王五";
        objects[1] = "zzzzzz";
        jdbcTemplate.update(sql,objects);
        return "update~ok";
    }

    //删除用户
    @GetMapping("/deleteUser/{id}")
    public String deleteUser(@PathVariable("id") int id){
        String sql = "delete from mydb.user where id="+id;
        jdbcTemplate.update(sql);
        return "delete~ok";
    }

}
